package com.yunhe.device.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.CollectionUtil;
import com.yunhe.common.util.DateTimeUtils;
import com.yunhe.common.util.StringUtil;
import com.yunhe.device.domain.base.EquipmentAttributes;
import com.yunhe.device.domain.base.DeviceType;
import com.yunhe.device.model.base.EquipmentAttributesQueryCondition;
import com.yunhe.device.model.base.EquipmentAttributesVo;
import com.yunhe.device.model.base.StatusVo;
import com.yunhe.device.repository.base.EquipmentAttributesRepository;
import com.yunhe.device.repository.base.impl.EquipmentAttributesDao;
import com.yunhe.device.service.base.EquipmentAttributeService;
import com.yunhe.device.utils.BeansUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName EquipmentAttributeServiceImpl
 * @Description TODO
 * @Author HeTao
 * @Date 2021/7/15 12:39
 * @Version 1.0
 **/
@Service
@Slf4j
public class EquipmentAttributeServiceImpl implements EquipmentAttributeService {

    @Autowired
    private EquipmentAttributesRepository equipmentAttributesRepository;

    @Autowired
    private EquipmentAttributesDao equipmentAttributesDao;

    /**
     * 校验编码 名称是否重复
     * @param equipmentAttributes
     * @throws ArgumentErrorException
     * @throws UniqueConstraintsException
     * @throws ObjectNotFoundException
     */
    private void processBeforeSave(EquipmentAttributes equipmentAttributes)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        //判断设备属性类型代码、编号、标题是否为空
        if (StringUtil.isEmpty(equipmentAttributes.getName())
                || StringUtil.isEmpty(equipmentAttributes.getTitle())) {
            throw new ArgumentErrorException("设备属性编码、标题不能为空");
        }
        //判断代码是否已存在
        EquipmentAttributes typeByName = this.findByName(equipmentAttributes.getName());
        if (typeByName != null) {
            if (equipmentAttributes.getId() == null || typeByName.getId().longValue() != equipmentAttributes.getId().longValue()) {
                throw new UniqueConstraintsException("该设备属性编码已存在");
            }
        }
        //判断编号是否已存在
        EquipmentAttributes typeByTitle = this.findByTitle(equipmentAttributes.getTitle());
        if (typeByTitle != null) {
            if (equipmentAttributes.getId() == null || typeByTitle.getId().longValue() != equipmentAttributes.getId().longValue()) {
                throw new UniqueConstraintsException("该设备属性名称已存在");
            }
        }
    }

    private EquipmentAttributes findByTitle(String title) {
        return equipmentAttributesRepository.findByTitle(title);
    }

    private EquipmentAttributes findByName(String name) {
        return equipmentAttributesRepository.findByName(name);
    }

    @Override
    public EquipmentAttributes createEquipmentAttributes(EquipmentAttributes equipmentAttributes) throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException {
        equipmentAttributes.setId(null);
        String format = DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date());
        equipmentAttributes.setSn(DateTimeUtils.getTimestamp(format,null));
        equipmentAttributes.setCreateTime(format);
        equipmentAttributes.setInitData(true);
        processBeforeSave(equipmentAttributes);
        EquipmentAttributes newEquipmentAttributes = equipmentAttributesRepository.save(equipmentAttributes);
        return newEquipmentAttributes;
    }

    @Override
    public Iterable<EquipmentAttributesVo> getEquipmentAttributesByCondition(EquipmentAttributesQueryCondition equipmentAttributesQueryCondition) {
        Iterable<EquipmentAttributesVo> results = null;
        Page<EquipmentAttributes> equipmentAttributes = null;
        Pageable pageable = PageRequest.of(equipmentAttributesQueryCondition.getPage()-1, equipmentAttributesQueryCondition.getSize());
//        if (StringUtils.isEmpty(equipmentAttributesQueryCondition.getKeywords()) &&StringUtils.isEmpty(equipmentAttributesQueryCondition.getComponentType())) {
//            equipmentAttributes = equipmentAttributesRepository.findAll(pageable);
//        } else {
        equipmentAttributes = equipmentAttributesDao.getEquipmentAttributesByCondition(equipmentAttributesQueryCondition);
        //}
        if(equipmentAttributes != null){
            List<EquipmentAttributes> content = equipmentAttributes.getContent();
            List<EquipmentAttributesVo> equipmentAttributesVos = BeansUtil.listCopy(content, EquipmentAttributesVo.class);
            results = new PageImpl(equipmentAttributesVos,pageable,equipmentAttributes.getTotalElements());
        }
        return results;
    }

    @Override
    public EquipmentAttributesVo getEquipmentAttributesById(Long id) throws ObjectNotFoundException {
        EquipmentAttributesVo result  = new EquipmentAttributesVo();
        EquipmentAttributes equipmentAttributes = equipmentAttributesRepository.findById(id).orElse(null);
        if(equipmentAttributes == null){
            throw new ObjectNotFoundException("无此设备属性信息");
        }
        BeanUtils.copyProperties(equipmentAttributes,result);
        return result;
    }

    @Override
    public void deleteEquipmentAttributesById(Long id) throws ObjectNotFoundException, ArgumentErrorException {
        EquipmentAttributesVo equipmentAttributesById = getEquipmentAttributesById(id);
        if(equipmentAttributesById == null){
            throw new ObjectNotFoundException("无此设备属性信息");
        }
        //查询当前设备属性是否绑定设备类型如果绑定 不能删除
        List<DeviceType> equipmentTypes = equipmentAttributesRepository.findAnlogTypeById(id);
        if(!CollectionUtil.isEmpty(equipmentTypes)){
            throw new ArgumentErrorException("设备属性："+equipmentAttributesById.getTitle()+"已与相关设备类型绑定，不能删除！");
        }
        equipmentAttributesRepository.deleteById(id);
    }

    @Override
    public EquipmentAttributes updateEquipmentAttributes(EquipmentAttributes equipmentAttributes) throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException {
        EquipmentAttributes equipmentAttributesById = equipmentAttributesRepository.findById(equipmentAttributes.getId()).orElse(null);
        if(equipmentAttributesById == null){
            throw new ObjectNotFoundException("找不到对应设备属性信息");
        }
        equipmentAttributesById.setActivity(equipmentAttributes.getActivity());
        equipmentAttributesById.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
        equipmentAttributesById.setTitle(equipmentAttributes.getTitle());
        equipmentAttributesById.setComponentType(equipmentAttributes.getComponentType());
        equipmentAttributesById.setUrl(equipmentAttributes.getUrl());
        processBeforeSave(equipmentAttributesById);
        EquipmentAttributes newEquipmentAttributes = equipmentAttributesRepository.save(equipmentAttributesById);
        return newEquipmentAttributes;
    }

    @Override
    public void updateEquipmentAttributesStauts(StatusVo statusVo) throws ObjectNotFoundException, UniqueConstraintsException, ArgumentErrorException {
        List<Long> ids = statusVo.getIds();
        for (Long id : ids) {
            EquipmentAttributes equipmentAttributesById = equipmentAttributesRepository.findById(id).orElse(null);
            if(equipmentAttributesById == null){
                throw new ObjectNotFoundException("找不到对应设备属性信息");
            }
            equipmentAttributesById.setActivity(statusVo.getActivity());
            equipmentAttributesById.setUpdateTime(DateTimeUtils.format(DateTimeUtils.PATTERN.DATETIME.value(), new Date()));
            processBeforeSave(equipmentAttributesById);
            EquipmentAttributes newEquipmentAttributes = equipmentAttributesRepository.save(equipmentAttributesById);
        }
    }

    @Override
    public List<EquipmentAttributes> getEquipmentAttributesByEquipTypeName(String equipName) {
        if(StringUtil.isEmpty(equipName)){
            List<EquipmentAttributes> equipmentAttributes = equipmentAttributesRepository.findByActivityAndType("1", "01");
            if(!CollectionUtil.isEmpty(equipmentAttributes)){
                return equipmentAttributes.stream().filter(equipmentAttribute -> {
                    return !Arrays.asList("equipName","equipLocation","ownedPark","equipSN").contains(equipmentAttribute.getName());
                }).collect(Collectors.toList());
            }
            return null;
        }else {
            return equipmentAttributesRepository.getEquipmentAttributesByEquipTypeName(equipName);
        }
    }

    @Override
    public List<EquipmentAttributesVo> getEquipmentAttributesByEquipTypeId(Long id) {
        List<EquipmentAttributes> equipmentAttributes = equipmentAttributesRepository.getEquipmentAttributesByEquipTypeId(id);
        if(CollectionUtil.isEmpty(equipmentAttributes)){
            return null;
        }
        List<EquipmentAttributesVo> equipmentAttributesVos = BeansUtil.listCopy(equipmentAttributes, EquipmentAttributesVo.class);
        return equipmentAttributesVos;
    }

    @Override
    public List<Long> getEquipmentAttributesByName(List<String> names) {
        List<EquipmentAttributes> equipmentAttributes = equipmentAttributesRepository.findEquipmentAttributesByName(names);
        if(CollectionUtil.isEmpty(equipmentAttributes)){
            return null;
        }else {
            return equipmentAttributes.stream().map(EquipmentAttributes::getId).collect(Collectors.toList());
        }
    }
}
